﻿/* $RCSFile: CrmUtil4XmlImportExport.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/CRMWrapper3/CrmUtil4XmlImportExport.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:31  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Web.Services.Protocols;
using System.Globalization;

using CrmSdk.CRM4;

using AddonNice.CRMWrapper.Design;
using AddonNice.CRMWrapper.CRM4Server;
using AddonNice.CRMWrapper.CRM4Meta;

namespace AddonNice.CRMWrapper
{

	public class RetrieveFormXml
	{
	    
        public string formXml       =   string.Empty;
		public string entityName    =   string.Empty;

        public RetrieveFormXml(string entName)
		{
            entityName                          =   entName;
		}

		public bool Run(CrmWrapper4 wrapper)
		{
			RetrieveFormXmlRequest request      =   new RetrieveFormXmlRequest();
			request.EntityName                  =   entityName;
			RetrieveFormXmlResponse response    = (RetrieveFormXmlResponse)wrapper.adminAdminExecuteRaw(request);
			formXml                             =   response.FormXml;
			return (!String.IsNullOrEmpty(response.FormXml));
		}
	}

    public enum ImportExportType { entities,nodes,sitemap,isvconfigxml,securityroles,settings,workflows};

    /// <summary>
    /// Utility class to manage import and export of Crm Xml datas
    /// </summary>
    public class ImportExportXml
	{
	    public string DataXml                       =   string.Empty;
		public string entityName                    =   string.Empty;
	    public string RequestParameter              =   "<entities><entity>{0}</entity></entities><nodes/><securityroles/><settings/><workflows/>"; // default to entities
        public const string RequestParameterISV     =   "<entities></entities><nodes><node>isvconfig</node></nodes><securityroles/><settings/><workflows/>";        
        public const string RequestParameterSiteMap =   "<entities></entities><nodes><node>sitemap</node></nodes><securityroles/><settings/><workflows/>";        

        public string strErr                        =   string.Empty;
        public ImportExportType Type                =   ImportExportType.entities; //default

        /// <summary>
        /// Ctor to export data from CRM using default parameters (only entities)
        /// </summary>
        public ImportExportXml(string entName)
		{
            entityName                  =   entName;
		}

        public ImportExportXml(ImportExportType tp)
		{
            Type                        =   tp;
		}

        /// <summary>
        /// Ctor to import data to CRM using default parameters (only entities)
        /// </summary>
        public ImportExportXml(string entName,string dataXml)
		{
            entityName                  =   entName;
            DataXml                     =   dataXml;
		}

        public ImportExportXml(ImportExportType tp,string dataXml)
		{
            DataXml                     =   dataXml;
            Type                        =   tp;
		}
   
        /// <summary>
        /// Ctor to import data to CRM using special parameters configuration
        /// </summary>
        public ImportExportXml(string entName,string dataXml,string requestParameter)
		{
            entityName                  =   entName;
            DataXml                     =   dataXml;
            RequestParameter            =   requestParameter;
		}

        /// <summary>
        /// Export selected customization data from Crm (entities,isvconfigxml,sitemap) in DataXml property of this object
        /// </summary>
        public bool Export(CrmWrapper4 wrapper)
		{
            if ( CRMMetaTrace.Sw.TraceVerbose || InstallTraceSwitchW.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ImportExportXml Export BEG Type: '{0}'", Type),(CRMMetaTrace.Sw.TraceVerbose) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
			bool success                    =   false;
			try
			{
				ExportXmlRequest exportRequest = new ExportXmlRequest();
                string fmt                  =   RequestParameter;
                switch (Type)
                {
                    case ImportExportType.entities:
                        fmt                 =   string.Format(RequestParameter, entityName);
                        break;
                    case ImportExportType.isvconfigxml:
                        fmt                 =   RequestParameterISV;
                        break;
                    case ImportExportType.sitemap:
                        fmt                 =   RequestParameterSiteMap;
                        break;
                    default:
                        string msg  =   string.Format("[E]ImportExportXml Export Not Supported Type: '{0}'", Type);
                        if ( CRMMetaTrace.Sw.TraceError || InstallTraceSwitchW.Sw.TraceError )
                            Trace.WriteLine( msg,(CRMMetaTrace.Sw.TraceError) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
                        throw new ArgumentException(msg);
                }
                if ( CRMMetaTrace.Sw.TraceVerbose || InstallTraceSwitchW.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ImportExportXml Export Fmt: '{0}'", fmt),(CRMMetaTrace.Sw.TraceVerbose) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
				// Define the entities to retrieve
				// The XML format must match this and the empty "nodes" node is required.
				exportRequest.ParameterXml  =   string.Format("<importexportxml>{0}</importexportxml>",fmt);
				ExportXmlResponse entities  =   (ExportXmlResponse)wrapper.adminAdminExecuteRaw(exportRequest);
                DataXml                     =   entities.ExportXml;
				success                     =   true;
			}
			catch (SoapException sex)
			{
                strErr                      =   ErrorCodes.GetErrorMessage(sex);
				success                     =   false;
                if ( CRMMetaTrace.Sw.TraceError || InstallTraceSwitchW.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ImportExportXml Export sex: {0}", sex.Detail.InnerText),(CRMMetaTrace.Sw.TraceError) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
                throw;
			}
			catch (Exception ex)
			{
                if ( CRMMetaTrace.Sw.TraceError || InstallTraceSwitchW.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ImportExportXml Export ex: {0}",ex),(CRMMetaTrace.Sw.TraceError) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
                throw;
			}
            if ( CRMMetaTrace.Sw.TraceVerbose || InstallTraceSwitchW.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ImportExportXml Export END ret: {0}", success),(CRMMetaTrace.Sw.TraceVerbose) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
			return success;
		}
				
		/// <summary>
		/// Import ISV Data contained in DataXml property to CRM, publish if requested
		/// </summary>
        public bool Import(CrmWrapper4 wrapper,bool publish)
		{
            if ( CRMMetaTrace.Sw.TraceVerbose || InstallTraceSwitchW.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ImportExportXml Import BEG Type: {0}, publish: {1}", Type,publish),(CRMMetaTrace.Sw.TraceVerbose) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
			bool success                            =   false;
			try
			{
				// Build the XML string that defines what cusomization to import and publish.
                string fmt                          =   RequestParameter;
                switch (Type)
                {
                    case ImportExportType.entities:
                        fmt                         =   string.Format(RequestParameter, entityName);
                        break;
                    case ImportExportType.isvconfigxml:
                        fmt                         =   RequestParameterISV;
                        break;
                    case ImportExportType.sitemap:
                        fmt                         =   RequestParameterSiteMap;
                        break;
                    default:
                        string msg                  =   string.Format("[E]ImportExportXml Import Not Supported Type: '{0}'", Type);
                        if ( CRMMetaTrace.Sw.TraceError || InstallTraceSwitchW.Sw.TraceError )
                            Trace.WriteLine( msg,(CRMMetaTrace.Sw.TraceError) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
                        throw new ArgumentException(msg);
                }
                if ( CRMMetaTrace.Sw.TraceVerbose || InstallTraceSwitchW.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ImportExportXml Import Fmt: '{0}'", fmt),(CRMMetaTrace.Sw.TraceVerbose) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
				string ParameterXml                 =   string.Format("<importexportxml>{0}</importexportxml>",fmt);
				ImportXmlRequest importRequest      =   new ImportXmlRequest();
				importRequest.CustomizationXml      =   DataXml;
				importRequest.ParameterXml          =   ParameterXml;
	
				ImportXmlResponse importResponse    =  (ImportXmlResponse)wrapper.adminAdminExecuteRaw(importRequest);

				// Publish the imported customizations.
                if ( publish )
                {
                    PublishXmlRequest pXmlRequest   =   new PublishXmlRequest();
                    pXmlRequest.ParameterXml        =   ParameterXml;

                    wrapper.adminAdminExecuteRaw(pXmlRequest);
                    success                         =   true;
                }
                else success                        =   true;
			}
			catch (SoapException sex)
			{
                strErr                              =   ErrorCodes.GetErrorMessage(sex);
				success                             =   false;
                if ( CRMMetaTrace.Sw.TraceError || InstallTraceSwitchW.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ImportExportXml Import sex: {0}", sex.Detail.InnerText),(CRMMetaTrace.Sw.TraceError) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
			}
			catch (CRMWrapperException wex)
			{
                if ( ( wex.InnerException != null ) && ( wex.InnerException is SoapException ) )
                {
                    SoapException sx                =   (SoapException)wex.InnerException;
                    strErr                          =   ErrorCodes.GetErrorMessage(sx);
                    success                         =   false;
                    if ( CRMMetaTrace.Sw.TraceError || InstallTraceSwitchW.Sw.TraceError )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ImportExportXml Import sex: {0}",sx.Detail.InnerText),(CRMMetaTrace.Sw.TraceError) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
                }
                else throw;
			}
			catch (Exception ex)
			{
                if ( CRMMetaTrace.Sw.TraceError || InstallTraceSwitchW.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ImportExportXml Import ex: {0}",ex),(CRMMetaTrace.Sw.TraceError) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
                throw;
			}
            if ( CRMMetaTrace.Sw.TraceVerbose || InstallTraceSwitchW.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ImportExportXml Import END ret: {0}", success),(CRMMetaTrace.Sw.TraceVerbose) ?  CRMMetaTrace.Sw.Info:  InstallTraceSwitchW.Sw.Info);
			return success;
		}
	}
}